// import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'
import { read } from './assets/Axios/axiosH'
import pin from 'pinia-plugin-persistedstate'
import { useCounterStore } from '@/stores/counter'


// 配置后端API基础路径
// 统一使用 Vite 约定的前缀 VITE_ 环境变量
axios.defaults.baseURL = (import.meta as any).env.VITE_API_BASE_URL || '/api';

read.defaults.headers.common["Authorization"] = "Bearer " + window.localStorage.getItem("token");

const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
// create pinia instance and register persisted state plugin
const pinia = createPinia()
pinia.use(pin)
app.use(pinia)

// 如果 localStorage 有 token，初始化 store 和 axios 的 header
try {
  const counterStore = useCounterStore()
  const savedToken = window.localStorage.getItem('token')
  if (savedToken) {
    counterStore.Logins.token = savedToken
    axios.defaults.headers.common["Authorization"] = `Bearer ${savedToken}`
    read.defaults.headers.common["Authorization"] = `Bearer ${savedToken}`
  }
} catch (e) {
  // 在某些环境下（SSR 或测试）useCounterStore 可能不可用；忽略初始化错误
}
app.use(router)
app.use(ElementPlus, {
  locale: zhCn,
})
app.mount('#app')
